package com.haibara.aiojquestionservice.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haibara.aiojcommon.common.ErrorCode;
import com.haibara.aiojcommon.constant.CommonConstant;
import com.haibara.aiojcommon.exception.BusinessException;
import com.haibara.aiojcommon.utils.SqlUtils;
import com.haibara.aiojfeignclient.client.JudgeClient;
import com.haibara.aiojfeignclient.client.UserClient;
import com.haibara.aiojmodel.model.dto.questionsubmit.JudgeInfo;
import com.haibara.aiojmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.haibara.aiojmodel.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.haibara.aiojmodel.model.entity.Question;
import com.haibara.aiojmodel.model.entity.QuestionSubmit;
import com.haibara.aiojmodel.model.entity.User;
import com.haibara.aiojmodel.model.enums.QuestionSubmitLanguageEnum;
import com.haibara.aiojmodel.model.enums.QuestionSubmitStatusEnum;
import com.haibara.aiojmodel.model.vo.QuestionSubmitVO;
import com.haibara.aiojmodel.model.vo.QuestionSubmitViewVO;
import com.haibara.aiojquestionservice.mapper.QuestionSubmitMapper;
import com.haibara.aiojquestionservice.service.QuestionService;
import com.haibara.aiojquestionservice.service.QuestionSubmitService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.haibara.aiojcommon.constant.UserConstant.USER_LOGIN_STATE;


/**
* @author AiChan
* @description 针对表【question_sumbit(题目提交)】的数据库操作Service实现
* @createDate 2023-12-20 13:17:36
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;

    @Resource
    private JudgeClient judgeClient;
    @Resource
    private UserClient userClient;

    /**
     * 点赞
     *
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 判断编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(enumByValue == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未知语言");
        }
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        question.setSubmitNum(question.getSubmitNum()+1);
        questionService.updateById(question);
        long userId = loginUser.getId();
        // 锁必须要包裹住事务方法
        QuestionSubmitService questionSubmitService = (QuestionSubmitService) AopContext.currentProxy();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setUserId(userId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(questionSubmitAddRequest.getLanguage());
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据插入失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        // 进行判题
        CompletableFuture.runAsync(()->{
            judgeClient.doJudge(questionSubmitId);
        });
        return questionSubmitId;
    }

    /**
     * 获取查询包装类
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        String sortField = questionSubmitQueryRequest.getSortField();
        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(language), "language", language);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 脱敏：仅本人和管理员能看见自己（提交 userId 和登录用户 id 不同）提交的代码
        long userId = loginUser.getId();
        // 处理脱敏
        if (userId != questionSubmit.getUserId() && !userClient.isAdmin(loginUser) ) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVoPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVoPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVoPage.setRecords(questionSubmitVOList);
        return questionSubmitVoPage;
    }

    @Override
    public Page<QuestionSubmitViewVO> listQuestionSubmitByPage(String title, String language, long pageIndex, long size) {
        Page<QuestionSubmitViewVO> page = new Page<>(pageIndex, size);
        long total = this.baseMapper.countQuestionSubmit(title, language);
        page.setTotal(total);
        if (size > 0) {
            page.setPages(total / size);
        }
        List<QuestionSubmitViewVO> records = this.baseMapper.selectQuestionSubmit(title, language, pageIndex, size);
        records.forEach(record -> {
            JudgeInfo judgeInfo = JSONUtil.toBean(record.getJudgeInfo(), JudgeInfo.class);
            record.setMemory(ObjectUtil.defaultIfNull(judgeInfo.getMemory(), 0) + "MB");
            record.setMessage(judgeInfo.getMessage());
            record.setTime(ObjectUtil.defaultIfNull(judgeInfo.getTime(), 0) + "ms");
        });
        page.setRecords(records);
        return page;
    }

    @Override
    public String getHistoryCode(Long questionId,HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        Long id = loginUser.getId();
        return this.baseMapper.getHistoryCode(questionId, id);
    }

    @Override
    public String getExampleCode(Long questionId) {
        Question byId = questionService.getById(questionId);
        return byId.getExampleCode();
    }


}




